package com.zcsy.manage.owner.controller.system;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zcsy.commons.mobile.MobileConfig;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.commons.util.Globals;
import com.zcsy.manage.model.base.CellBuilding;
import com.zcsy.manage.model.base.CellHouse;
import com.zcsy.manage.model.base.CellInfo;
import com.zcsy.manage.model.base.CellRegion;
import com.zcsy.manage.model.base.CellUnit;
import com.zcsy.manage.model.base.CommonToken;
import com.zcsy.manage.model.base.CommonVerifyCode;
import com.zcsy.manage.model.base.OwnerHouse;
import com.zcsy.manage.model.system.DistrictInfo;
import com.zcsy.manage.model.system.User;
import com.zcsy.commons.constants.OwnerConstants;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.constants.DistributionConstants;
import com.zcsy.commons.ehcache.CacheUtils;
import com.zcsy.manage.owner.service.base.IOCommonVerifyCodeService;
import com.zcsy.manage.owner.service.common.IOCommonTokenService;
import com.zcsy.manage.owner.service.system.IOUserService;
import com.zcsy.manage.service.base.ICellBuildingService;
import com.zcsy.manage.service.base.ICellHouseService;
import com.zcsy.manage.service.base.ICellInfoService;
import com.zcsy.manage.service.base.ICellRegionService;
import com.zcsy.manage.service.base.ICellUnitService;
import com.zcsy.manage.service.mall.IIntegralConfigService;
import com.zcsy.manage.service.mall.IIntegralRecordService;
import com.zcsy.manage.service.property.IRepairInfoService;
import com.zcsy.manage.service.sms.DlifeSmsService;
import com.zcsy.manage.service.system.IDistrictInfoService;
import com.zcsy.manage.service.system.IUserService;

/**
 * @Title: UserController.java
 * @Package： com.zcsy.manage.owner.controller.system
 * @Description: 用户管理
 * @author liuziyu liuziyuwri@foxmail.com
 * @Copyright: 2016 武汉恒数利通软件有限公司 All rights reserved.
 * @date 2016年6月23日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Controller
@RequestMapping(value = "user")
public class UserController {

	@Autowired
	private DlifeSmsService dlifeSmsService;

	@Autowired
	private IOCommonVerifyCodeService commonVerifyCode;

	@Autowired
	private IOUserService ouserService;

	@Autowired
	private IOCommonTokenService commomTokenService;

	@Autowired
	private ICellHouseService cellHouseService;

	@Autowired
	private IUserService userService;
	
	@Autowired
	private IRepairInfoService repairInfoService;
	
	@Autowired
	private IDistrictInfoService districtInfoService;
	
	@Autowired
	private ICellInfoService cellInfoService;
	
	@Autowired
	private ICellBuildingService cellBuildingService;
	
	@Autowired
	private ICellUnitService cellUnitService;
	
	@Autowired
	private IIntegralRecordService integralRecordService;
	
	@Autowired
	private ICellRegionService cellRegionService;

	/**
	 * @Description <br>
	 * 
	 * @param loginName
	 *            账号名（包括：1、登录名 2、手机号）
	 * @param password
	 *            账号密码
	 * @param platformType
	 *            客户端类型:1.Android;2.iOS
	 * @param userType
	 *            用户类型：0平台,1运营，2物业，3商家，4配送，5业主
	 * @return
	 * @throws ParseException
	 * @author caiyinli 13277030520@163.com
	 * @date 2016年6月23日
	 * @see
	 */
	@RequestMapping(value = "userLogin")
	@ResponseBody
	public RequestJson userLogin(String loginName, String password,
			Integer platformType, Integer userType) {
		RequestJson result = new RequestJson();

		try {
			User user = new User();
			user.setPhone(loginName);
			user.setUserType(userType);
			User loginUser = ouserService.ownerUserLogin(user);

			if (loginUser == null) {
				result.setSuccess(false);
				result.setResultCode(OwnerConstants.USER_NOT_EXIST);
				result.setMsg("帐号不存在！");
			}else if(loginUser.getState() != OwnerConstants.OWNER_USER_STATE){
				result.setSuccess(false);
				result.setResultCode(OwnerConstants.USER_FORBID);
				result.setMsg("该业主已停用！");
				
			}else if (loginUser.getPwd() != null) {
				if (loginUser.getPwd().equals(password)) {
					// 获取过期时间间隔30分钟
					String expire = MobileConfig.getMOBILE_TOKEN_EXPIRE();
					Integer expireInteger = Integer.valueOf(expire);

					CommonToken token = new CommonToken();
					Date creatTime = new Date();
					token.setCreateTime(creatTime);
					Calendar cal = Calendar.getInstance();
					cal.setTime(creatTime);
					cal.add(Calendar.MINUTE, expireInteger);
					Date expireTime = cal.getTime();
					token.setExpireTime(expireTime);
					token.setPlatformType(platformType);
					token.setUserType(userType);

					// 插入或更新token
					if (loginUser.getLoginname() != null) {
						if (commomTokenService.selectByAccount(loginUser
								.getLoginname()) == null) {
							token.setToken(UniqueNumberUtils.get18UniqueNumber());
							token.setId(UniqueNumberUtils.get18UniqueNumber());
							token.setAccount(loginUser.getLoginname());
							commomTokenService.insert(token);
						} else {
							//让token不失效
							token = commomTokenService.selectByAccount(loginUser.getLoginname());
							token.setCreateTime(creatTime);
							token.setExpireTime(expireTime);
							token.setPlatformType(platformType);
							commomTokenService.updateToken(token);
						}
					}

					// 获取业主房屋信息
					List<CellHouse> houses = cellHouseService.getCellHouses(loginUser.getId());
							
					loginUser.setHouses(houses);
					
					Map<String, Object> map = new HashMap<String, Object>();
					
					//获取默认小区（即默认第一个房屋所在的小区）
					/*if(CollectionUtils.isNotEmpty(houses) && houses.size() > 0){
						CellHouse cellHouse = houses.get(0);
						if(cellHouse != null){
							CellInfo cellInfo = cellInfoService.selectByPrimaryKey(cellHouse.getCellId());
							map.put("cellInfo", cellInfo);
						}
					}*/
					
					// 用户登录一次就改变登录次数及时间
					loginUser.setLoginTimes(loginUser.getLoginTimes() + 1);
					loginUser.setLastLoginTime(DateUtils.gettimestamp());
	                userService.updateByPrimaryKeySelective(loginUser);
					
					map.put("user", loginUser);
					map.put("token", token.getToken());
					map.put("imageurl", Globals.getImageUrl());

					result.setSuccess(true);
					result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
					result.setMsg("登录成功！");
					result.setObj(map);
				} else {
					result.setSuccess(false);
					result.setResultCode(OwnerConstants.RESULT_PASSWORD_FALSE);
					result.setMsg("密码错误！");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
			result.setMsg("网络异常");
		}

		return result;

	}

	/**
	 * @Description 业主注册<br>
	 * 
	 * @param phone
	 *            手机号
	 * @param code
	 *            验证码
	 * @param nickName
	 *            昵称
	 * @param userName
	 *            真实姓名
	 * @param password
	 *            密码
	 * @return 返回业主信息
	 * @author caiyinli 13277030520@163.com
	 * @date 2016年6月24日
	 * @see
	 */
	@RequestMapping(value = "userRegister")
	@ResponseBody
	public RequestJson userRegister(String phone, String code, String nickName,
			String userName, String password) {
		RequestJson result = new RequestJson();

		try {
			CommonVerifyCode record = commonVerifyCode.selectCodeByPhone(phone);
			List<User> userExit = userService.selectUserIfPhoneExists(phone, OwnerConstants.OWNER_USER_TYPE);
			if(userExit != null && userExit.size() > 0){
				result.setSuccess(false);
				result.setResultCode(OwnerConstants.CODE_IS_FALSE);
				result.setMsg("该手机号已被注册！");
				return result;
			}
			if (null != record && null != record.getCode()) {
				if (code.equals(record.getCode())) {
					User user = new User();
					user.setNickname(nickName);
					user.setUsername(userName);
					user.setPwd(password);
					user.setPhone(phone);
					user.setUserType(OwnerConstants.OWNER_USER_TYPE);
					user.setId(UniqueNumberUtils.get18UniqueNumber());
					user.setCreatedatetime(DateUtils.gettimestamp());
					user.setState(OwnerConstants.USER_STATE);
					//登录次数置0
					user.setLoginTimes(0);
					//积分置0
					user.setIntegral(0);
					// 自动生成帐户编号
					String account = userService
							.getNewUserNo(Constants.OWNER_TYPE);
					user.setLoginname(account);

					int flag = userService.insert(user);
					if (flag == Constants.SQL_RESULT_SUCCESS) {
						result.setSuccess(true);
						result.setResultCode(OwnerConstants.OWNER_REGISTER_SUCCESS);
						result.setMsg("注册成功");
						result.setObj(user);
						
						//刚注册的业主发送验证码时，没有登录名，所以注册成功之后插入业主登录名
						record.setUserAccount(user.getLoginname());
						commonVerifyCode.update(record);
						
						//注册成功后增加相应积分
						integralRecordService.changeIntegralMethod(record.getUserAccount() , OwnerConstants.INTEGRAL_REGISTER);
						
					} else {
						result.setSuccess(false);
						result.setResultCode(OwnerConstants.OWNER_REGISTER_FALSE);
						result.setMsg("注册失败");
						
						//如果注册不成功，就将发送给该业主的验证码删掉
						commonVerifyCode.deleteById(record.getId());
					}

				} else {

					result.setSuccess(false);
					result.setResultCode(OwnerConstants.CODE_IS_FALSE);
					result.setMsg("验证码输入错误！");
				}
			} else {
				result.setSuccess(false);
				result.setResultCode(OwnerConstants.CODE_IS_FALSE);
				result.setMsg("验证码获取失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
			result.setMsg("网络异常");

		}
		return result;
	}

	/**
	 * @Description 房屋注册<br>
	 * 
	 * @param provinceId
	 *            省id
	 * @param cityId
	 *            市id
	 * @param cellId
	 *            小区id
	 * @param regionId
	 *            区域id
	 * @param buildingId
	 *            楼栋id
	 * @param unitId
	 *            单元id
	 * @param houseId
	 *            门牌号
	 * @param token
	 * @return 1：注册成功 0：注册失败
	 * @author caiyinli 13277030520@163.com
	 * @date 2016年6月27日
	 * @see
	 */
	@RequestMapping(value = "houseRegister")
	@ResponseBody
	public RequestJson houseRegister(String cellId, String houseId, String token) {
		RequestJson result = new RequestJson();

		try {
			//根据token查用户登录名
			result = commomTokenService.OrderInteractState(token , result);
			if(result.isSuccess()){
				//通过token获取用户信息
				CommonToken tokenInfo = commomTokenService.selectByToken(token);
				String loginname = tokenInfo.getAccount();
				User user = userService.selectByLoginName(loginname);
				if (user != null) {
					OwnerHouse recordHouse = cellHouseService
							.getByOHouseStateByOwnerIdAndHouseId(user.getId(),
									houseId);
					if (recordHouse != null && recordHouse.getState() != OwnerConstants.NOPASS_HOUSE_STATE 
							&& recordHouse.getState() != OwnerConstants.NOBOUND_HOUSE_STATE ) {
						switch (recordHouse.getState()) {
						case OwnerConstants.NEWAPPLY_HOUSE_STATE:
							result.setSuccess(false);
							result.setResultCode(OwnerConstants.HOUSE_REGISTER_FALSE);
							result.setMsg("该房屋已注册，审核中！");
							break;
						case OwnerConstants.NORMAL_HOUSE_STATE:
							result.setSuccess(false);
							result.setResultCode(OwnerConstants.HOUSE_REGISTER_FALSE);
							result.setMsg("您已注册该房屋");
							break;
						case OwnerConstants.FORBID_HOUSE_STATE:
							result.setSuccess(false);
							result.setResultCode(OwnerConstants.HOUSE_REGISTER_FALSE);
							result.setMsg("该房屋已禁用");
							break;
						}
						
					} else {
						//当前选择的房屋没有与该业主绑定，或者绑定了房屋状态为审核未通过或已解绑
						int flag = Constants.SQL_RESULT_FAILD;
						OwnerHouse ownerHouse = new OwnerHouse();
						if(recordHouse == null){
							ownerHouse.setCellId(cellId);
							ownerHouse.setHouseId(houseId);
							ownerHouse.setOwnerId(user.getId());
							//新申请
							ownerHouse.setState(OwnerConstants.NEWAPPLY_HOUSE_STATE);
							ownerHouse.setId(UniqueNumberUtils.get18UniqueNumber());
							
							flag = cellHouseService.insertOwnerHouse(ownerHouse);
							if(flag == Constants.SQL_RESULT_SUCCESS){
								result.setSuccess(true);
								result.setResultCode(OwnerConstants.HOUSE_REGISTER_SUCCESS);
								result.setMsg("已提交申请，请敬候佳音");
								result.setObj(ownerHouse);
							}else {
								result.setSuccess(false);
								result.setResultCode(OwnerConstants.HOUSE_REGISTER_FALSE);
								result.setMsg("房屋注册失败");
								result.setObj(ownerHouse);
							}
						}else if(recordHouse != null && recordHouse.getState() == OwnerConstants.NOPASS_HOUSE_STATE){
							//审核未通过再注册，状态修改为新申请
							flag = cellHouseService.updateOHouseStateByOwnerIdAndHouseId(user.getId(), houseId,OwnerConstants.NEWAPPLY_HOUSE_STATE);
							if(flag == Constants.SQL_RESULT_SUCCESS){
								result.setSuccess(true);
								result.setResultCode(OwnerConstants.HOUSE_REGISTER_SUCCESS);
								result.setMsg("已提交申请，请敬候佳音");
								result.setObj(recordHouse);
							}else {
								result.setSuccess(false);
								result.setResultCode(OwnerConstants.HOUSE_REGISTER_FALSE);
								result.setMsg("房屋注册失败");
								result.setObj(recordHouse);
							}
						}else if(recordHouse != null && recordHouse.getState() == OwnerConstants.NOBOUND_HOUSE_STATE){
							//已解绑再注册，状态修改为新申请
							flag = cellHouseService.updateOHouseStateByOwnerIdAndHouseId(user.getId(), houseId,OwnerConstants.NEWAPPLY_HOUSE_STATE);
							if(flag == Constants.SQL_RESULT_SUCCESS){
								result.setSuccess(true);
								result.setResultCode(OwnerConstants.HOUSE_REGISTER_SUCCESS);
								result.setMsg("已提交申请，请敬候佳音");
								result.setObj(recordHouse);
							}else {
								result.setSuccess(false);
								result.setResultCode(OwnerConstants.HOUSE_REGISTER_FALSE);
								result.setMsg("房屋注册失败");
								result.setObj(recordHouse);
							}
						}
					}

				}
			}

		} catch (Exception e) {
			result.setSuccess(false);
			result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
			result.setMsg("网络异常");

		}
		return result;
	}



	/**
	 * @Description 获取验证码<br>
	 * 
	 * @param phone
	 *            手机号
	 * @param operateType 操作类型，1找回密码2绑定手机3注册4验证原手机号
	 * @param token 只有绑定手机才传token
	 * @return resultCode=0:成功 resultCode=其他：失败
	 * @author caiyinli 13277030520@163.com
	 * @date 2016年6月27日
	 * @see 
	 */
	@RequestMapping(value = "getVerification")
	@ResponseBody
	public RequestJson getVerification(String phone,Integer operateType,String token) {

		RequestJson result = new RequestJson();

		//找回密码
		if(operateType == OwnerConstants.FIND_PASSWORD){
			List<User> userPhone = userService.selectUserIfPhoneExists(phone, OwnerConstants.OWNER_USER_TYPE);
			if(CollectionUtils.isEmpty(userPhone)){
				result.setMsg("手机号不存在!");
				result.setResultCode(DistributionConstants.PHONE_NOT_EXIST);
				result.setSuccess(false);
			}else if(userPhone != null && userPhone.size() > 0){
				//如果改用户的验证码记录存在，则删除，重新插入
			    CommonVerifyCode code = commonVerifyCode.selectCodeByPhone(phone);
				if (code != null) {
					commonVerifyCode.deleteById(code.getId());
				}
				CommonVerifyCode verifyCode = new CommonVerifyCode();
				
				Map<String, Object> map = this.generateCode(phone);
				verifyCode = (CommonVerifyCode)map.get("verifyCode");
				verifyCode.setUserAccount(userPhone.get(0).getLoginname());
				verifyCode.setOperateType(operateType);
				commonVerifyCode.insert(verifyCode);
				
				result.setMsg("获取成功！");
				result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
				result.setSuccess(true);
				result.setObj(map.get("code"));
				
			}

			//绑定手机
		}else if(operateType == OwnerConstants.BOUND_PHONE){
			result = commomTokenService.OrderInteractState(token, result);
			if(result.isSuccess()){
				CommonToken tokenInfo = commomTokenService.selectByToken(token);
				String loginname = tokenInfo.getAccount();
				User user = userService.selectByLoginName(loginname);
				if(user != null){
					if(phone.equals(user.getPhone())){
						result.setMsg("改手机号已绑定，无需再绑定!");
						result.setResultCode(DistributionConstants.PHONE_NOT_EXIST);
						result.setSuccess(false);
					}else{
						//如果改用户的验证码记录存在，则删除，重新插入
					    CommonVerifyCode code = commonVerifyCode.selectCodeByPhone(phone);
						if (code != null) {
							commonVerifyCode.deleteById(code.getId());
						}
						CommonVerifyCode verifyCode = new CommonVerifyCode();
						
						Map<String, Object> map = this.generateCode(phone);
						verifyCode = (CommonVerifyCode)map.get("verifyCode");
						verifyCode.setUserAccount(user.getLoginname());
						commonVerifyCode.insert(verifyCode);
						
						result.setMsg("获取成功！");
						result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
						result.setSuccess(true);
						result.setObj(map.get("code"));
					}
				}
				
			}
		}else if(operateType == OwnerConstants.REGISTER){
			List<User> userPhone = userService.selectUserIfPhoneExists(phone, OwnerConstants.OWNER_USER_TYPE);
			if(CollectionUtils.isNotEmpty(userPhone)){
				result.setMsg("改手机号已注册，请更换手机号!");
				result.setResultCode(DistributionConstants.PHONE_NOT_EXIST);
				result.setSuccess(false);
			}else{
				CommonVerifyCode verifyCode = new CommonVerifyCode();
				
				Map<String, Object> map = this.generateCode(phone);
				verifyCode = (CommonVerifyCode)map.get("verifyCode");
				commonVerifyCode.insert(verifyCode);
				
				result.setMsg("获取成功！");
				result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
				result.setSuccess(true);
				result.setObj(map.get("code"));
				
			}
		}else if (operateType == OwnerConstants.IDENTIFY_OLD_PHONE) {
			result = commomTokenService.OrderInteractState(token, result);
			if (result.isSuccess()) {
				List<User> userPhone = userService.selectUserIfPhoneExists(phone, OwnerConstants.OWNER_USER_TYPE);
				if(CollectionUtils.isEmpty(userPhone)){
					result.setMsg("手机号不存在!");
					result.setResultCode(DistributionConstants.PHONE_NOT_EXIST);
					result.setSuccess(false);
				}else if(userPhone != null && userPhone.size() > 0){
					CommonToken tokenInfo = commomTokenService.selectByToken(token);
					String loginname = tokenInfo.getAccount();
					User user = userService.selectByLoginName(loginname);
					if (user != null) {
						if(phone.equals(user.getPhone())){
							//如果改用户的验证码记录存在，则删除，重新插入
						    CommonVerifyCode code = commonVerifyCode.selectCodeByPhone(phone);
							if (code != null) {
								commonVerifyCode.deleteById(code.getId());
							}
							CommonVerifyCode verifyCode = new CommonVerifyCode();
							
							Map<String, Object> map = this.generateCode(phone);
							verifyCode = (CommonVerifyCode)map.get("verifyCode");
							verifyCode.setUserAccount(userPhone.get(0).getLoginname());
							commonVerifyCode.insert(verifyCode);
							
							result.setMsg("获取成功！");
							result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
							result.setSuccess(true);
							result.setObj(map.get("code"));
						}else{
							result.setMsg("获取失败！");
							result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
							result.setSuccess(false);
							result.setObj("");
						}
					}
					
					
				}
			}

		}
            
		return result;
	}


	/**
	 * @Description 用于封装获取验证码接口<br>
	 * 
	 * @param phone
	 *            手机号
	 * @return 返回验证码和验证码对象
	 * @author caiyinli 13277030520@163.com
	 * @date 2016年6月27日
	 * @see 
	 */
	public Map<String, Object> generateCode(String phone) {

		Date date = new Date();
		int count =( new Random()).nextInt(999999);
		if (count<100000) {
			count+=100000;
		}
		
		String content = count+"";
		String sendtime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date);
		Map<String,String> datas = dlifeSmsService.sendMsg(phone, content, sendtime);
		
		String expire = MobileConfig.getVERIFYCODE_EXPIRE();
		System.out.println(expire);
		Integer expireInteger = Integer.valueOf(expire);
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.MINUTE, expireInteger);
		Date expireTime = cal.getTime();
		
		CommonVerifyCode verifyCode = new CommonVerifyCode();
		verifyCode.setCode(content);
		verifyCode.setCreateTime(date);
		verifyCode.setId(UniqueNumberUtils.get18UniqueNumber());
		verifyCode.setExpireTime(expireTime);
		verifyCode.setPhone(phone);
		verifyCode.setUserType(Constants.DISTRIBUTION_TYPE);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", count);
		map.put("verifyCode", verifyCode);
		return map;
	}

	/**
	 * @Method: checkCode
	 * @Description 校验验证码(忘记密码处)
	 * @param phone
	 *            手机号
	 * @param code
	 *            验证码
	 * @return
	 * @author liuziyu liuziyuwri@foxmail.com
	 * @date 2016年6月24日
	 * @see
	 */
	@RequestMapping(value = "checkCode")
	@ResponseBody
	public RequestJson checkCode(String phone, String code) {
		RequestJson result = new RequestJson();

		String loginname = ouserService.selectLoginNameByPhone(phone);

		// 如果查询不到用户名
		if (StringUtils.isEmpty(loginname)) {
			result.setMsg("手机号未绑定帐号");
			result.setResultCode(OwnerConstants.PHONE_NOT_BIND_ACCOUNT);
			result.setSuccess(false);

		} else {
			CommonVerifyCode verifyCode = commonVerifyCode
					.selectCodeByPhone(phone);
			String codes = verifyCode.getCode();
			Date expireTime = verifyCode.getExpireTime();
			Date date = new Date();

			if ((date.compareTo(expireTime)) < 0) {

				if (code.equals(codes)) {
					result.setMsg("校验成功！");
					result.setResultCode(OwnerConstants.CODE_VERIFY_SUCCESS);
					result.setSuccess(true);

				} else {
					result.setMsg("输入验证码有误！");
					result.setSuccess(false);
					result.setResultCode(OwnerConstants.CODE_IS_FALSE);

				}
			} else {
				result.setMsg("验证码失效，请重新获取");
				result.setSuccess(false);
				result.setResultCode(DistributionConstants.CODE_IS_INVALIDE);

			}

		}

		return result;
	}

	/**
	 * token过期返回接口，主要提供给拦截器使用
	 * @return
	 * @author: zt
	 * @date: 2016年6月27日
	 */
	@RequestMapping(value = "tokenIsExpire")
	@ResponseBody
	public RequestJson tokenIsExpire(Integer tokenMessage) {

		RequestJson result = new RequestJson();
		
			if (tokenMessage == OwnerConstants.TOKEN_CHANGED) {
				result.setResultCode(tokenMessage);
				result.setMsg("帐号在其他设备登录");
			}
			if (tokenMessage == OwnerConstants.TOKEN_EXPIRE) {
				result.setResultCode(tokenMessage);
				result.setMsg("用户授权失效请重新登录");
			}
		
		result.setSuccess(false);
		return result;
	}
	
	/**
	 * @Method: updatePassword
	 * @Description 修改密码
	 * @param opwd
	 *            原始密码
	 * @param token
	 * @param npwd
	 *            新密码
	 * @return
	 * @author liuziyu liuziyuwri@foxmail.com
	 * @date 2016年6月27日
	 * @see
	 */
	@RequestMapping(value = "updatePassword")
	@ResponseBody
	public RequestJson updatePassword(String opwd, String token, String npwd) {

		RequestJson result = new RequestJson();

		commomTokenService.OrderInteractState(token, result);
		if (result.isSuccess()) {
			CommonToken tokenInfo = commomTokenService.selectByToken(token);
			// 根据token查询登录名
			String loginname = tokenInfo.getAccount();

			if (StringUtils.isNotEmpty(loginname)) {
				String spwd = userService.selectByLoginName(loginname).getPwd();

				// 如果原始密码输入正确
				if (spwd.equals(opwd))  {
						Date date = new Date();
						User user = new User();
						user.setModifydatetime(date);
						user.setPwd(npwd);
						user.setLoginname(loginname);
						ouserService.changePwd(user);
						
						result.setSuccess(true);
						result.setResultCode(OwnerConstants.MODIFY_PASSWORD_SUCCESS);
						result.setMsg("修改成功！");
						
				} else {
						result.setSuccess(false);
						result.setMsg("原密码输入错误！");
						result.setResultCode(OwnerConstants.OLD_PASSWORD_FALSE);

					}
				}
			}

		return result;
	}
	
	/**
     * @Description 获取个人信息<br>
     * @param token
     * @return 个人信息
     * @author yangfan 373188993@qq.com
     * @date 2016年6月27日
     * @see JDK1.7.0_75
     */
    @RequestMapping(value = "getUserInfo")
    @ResponseBody
    public RequestJson getUserInfo(String token ) {
        
        RequestJson result = new RequestJson();
        
        try {
            //调用方法传入token，无此token返回result为false
            result = commomTokenService.OrderInteractState(token , result);
            
            if (result.isSuccess()) {
                CommonToken tokenInfo = commomTokenService.selectByToken(token);
                String loginname = tokenInfo.getAccount();
                User user = userService.selectByPhone(loginname);
                
                //给头像加上前缀
                user.setHeadimg(Globals.getImageUrl() + user.getHeadimg());
                
                result.setResultCode(OwnerConstants.GET_USERINFO_SUCCESS);
                result.setMsg("查看成功！");
                result.setObj(user);
            } else {
                result.setResultCode(OwnerConstants.GET_USERINFO_FALSE);
                result.setMsg("网络异常！");
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
            result.setMsg("网络异常");
        }

        return result;
    }
    

    /**
     * @Method: boundPhone
     * @Description 绑定手机
     * @param token
     * @param phone 手机号
     * @return 
     * @author liuziyu liuziyuwri@foxmail.com
     * @date 2016年6月27日
     * @see 
     */
    @RequestMapping(value = "boundPhone" )
	@ResponseBody
	public RequestJson boundPhone(String code , String token, String phone) {
		RequestJson result = new RequestJson();
		
		commomTokenService.OrderInteractState(token , result);
		if (result.isSuccess()) {
			CommonToken tokenInfo = commomTokenService.selectByToken(token);
			// 根据token获得用户名
			String loginname = tokenInfo.getAccount();
			
			CommonVerifyCode verifyCode = commonVerifyCode.selectCodeByAccount(loginname);
			// 获得数据库里的验证码
			String codes = verifyCode.getCode();
			Date expireTime = verifyCode.getExpireTime();
			Date date = new Date();
			
			if ((date.compareTo(expireTime))<0) {
				if (code.equals(codes)) {
					// 如果手机号不存在于数据库中
					if ((ouserService.selectUserIfPhoneExists(phone, OwnerConstants.OWNER_USER_TYPE)
							.size() == 0)){
						ouserService.boundPhone(phone, loginname);
						result.setMsg("绑定成功！");
						result.setResultCode(OwnerConstants.PHONE_BIND_SUCCESS);
						result.setSuccess(true);
						
					} else {
						result.setMsg("该手机已被占用，请重新输入！");
						result.setResultCode(OwnerConstants.PHONE_ALREADY_BIND);
						result.setSuccess(true);

					}
					
				}else {
					result.setMsg("输入验证码有误！");
					result.setSuccess(false);
					result.setResultCode(OwnerConstants.CODE_IS_FALSE);
					
				}
				
			}else{
				result.setMsg("验证码失效");
				result.setResultCode(OwnerConstants.CODE_IS_INVALIDE);
				result.setSuccess(false);
				
			}
				
		}
		
		return result;
	}
    
    /**
     * @Description 获取省、市级联<br>
     * 
     * @return 返回省、市列表
     * @author caiyinli 13277030520@163.com
     * @date 2016年6月27日
     * @see 
     */
    @RequestMapping(value = "getProvincesAndcities")
    @ResponseBody
    public RequestJson getProvincesAndcities() {
        
        RequestJson result = new RequestJson();
       
        try {
			List<DistrictInfo> provinces = null;
			provinces = (List<DistrictInfo>)CacheUtils.get(Constants.APP_CACHE, "getProvincesAndcities");
            if(provinces == null){
            	provinces = districtInfoService.getProvincesAndcities();
            	CacheUtils.put(Constants.APP_CACHE, "getProvincesAndcities", provinces);
            }
			
			result.setMsg("数据获取成功！");
			result.setResultCode(OwnerConstants.PHONE_BIND_SUCCESS);
			result.setSuccess(true);
			result.setObj(provinces);
		} catch (Exception e) {
			e.printStackTrace();
			result.setMsg("数据获取失败！");
			result.setResultCode(OwnerConstants.CODE_IS_FALSE);
			result.setSuccess(false);
		}
        

        return result;
    }
    
    /**
     * @Description 获取小区、区域列表<br>
     * 
     * @param cityId市id
     * @param regionType=1获取小区、区域列表，regionType=0只获取小区列表
     * @return 
     * @author caiyinli 13277030520@163.com
     * @date 2016年6月28日
     * @see 
     */
    @RequestMapping(value = "getCellsAndRegions")
    @ResponseBody
    public RequestJson getCellsAndRegions(String cityId,Integer regionType) {
        
        RequestJson result = new RequestJson();
       
        try {
        	List<CellInfo> cells = new ArrayList<CellInfo>();
        	if(regionType == OwnerConstants.CELL_TYPE){
        		//获取小区和区域列表
       		 cells = cellInfoService.getCellsAndRegions(cityId);
        	}else if(regionType == OwnerConstants.CELL_REGION_TYPE){
        		//获取小区列表
        		 cells = cellInfoService.getCells(cityId);
        	}
			result.setMsg("数据获取成功！");
			result.setResultCode(OwnerConstants.PHONE_BIND_SUCCESS);
			result.setSuccess(true);
			result.setObj(cells);
		} catch (Exception e) {
			e.printStackTrace();
			result.setMsg("数据获取失败！");
			result.setResultCode(OwnerConstants.CODE_IS_FALSE);
			result.setSuccess(false);
		}
        

        return result;
    }
    
    @RequestMapping(value = "getCellRegions")
    @ResponseBody
    public RequestJson getCellRegions(String cellId) {
        
        RequestJson result = new RequestJson();
       
        try {
        	List<CellRegion> cells = cellRegionService.getCellRegionByCellId(cellId);
			result.setMsg("数据获取成功！");
			result.setResultCode(OwnerConstants.PHONE_BIND_SUCCESS);
			result.setSuccess(true);
			result.setObj(cells);
		} catch (Exception e) {
			e.printStackTrace();
			result.setMsg("数据获取失败！");
			result.setResultCode(OwnerConstants.CODE_IS_FALSE);
			result.setSuccess(false);
		}
        

        return result;
    }
    
    @RequestMapping(value = "getCellBuilding")
    @ResponseBody
    public RequestJson getCellBuilding(String regionId) {
        
        RequestJson result = new RequestJson();
       
        try {
            List<CellBuilding> cellBuilding = cellBuildingService.getCellBuildingByRegionId(regionId);
            result.setMsg("数据获取成功！");
            result.setResultCode(OwnerConstants.PHONE_BIND_SUCCESS);
            result.setSuccess(true);
            result.setObj(cellBuilding);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg("数据获取失败！");
            result.setResultCode(OwnerConstants.CODE_IS_FALSE);
            result.setSuccess(false);
        }
        

        return result;
    }
    
    @RequestMapping(value = "getCellUnit")
    @ResponseBody
    public RequestJson getCellUnit(String buildingId) {
        
        RequestJson result = new RequestJson();
       
        try {
            List<CellUnit> cellUnit = cellUnitService.getCellUnitByBuildingId(buildingId);
            result.setMsg("数据获取成功！");
            result.setResultCode(OwnerConstants.PHONE_BIND_SUCCESS);
            result.setSuccess(true);
            result.setObj(cellUnit);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg("数据获取失败！");
            result.setResultCode(OwnerConstants.CODE_IS_FALSE);
            result.setSuccess(false);
        }
        

        return result;
    }

    @RequestMapping(value = "getCellHouse")
    @ResponseBody
    public RequestJson getCellHouse(String unitId) {
        
        RequestJson result = new RequestJson();
       
        try {
            List<CellHouse> cellHouse = cellHouseService.getCellHouseByUnitId(unitId);
            result.setMsg("数据获取成功！");
            result.setResultCode(OwnerConstants.PHONE_BIND_SUCCESS);
            result.setSuccess(true);
            result.setObj(cellHouse);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg("数据获取失败！");
            result.setResultCode(OwnerConstants.CODE_IS_FALSE);
            result.setSuccess(false);
        }
        

        return result;
    }
    
    /**
     * @Method: resetPassword 
     * @Description 重置密码
     * @param phone 手机号
     * @param code 验证码
     * @param pwd 新密码
     * @return 
     * @author liuziyu liuziyuwri@foxmail.com
     * @date 2016年6月27日
     * @see 
     */
	@RequestMapping(value = "resetPassword")
	@ResponseBody
	public RequestJson resetPassword(String phone , String code , String pwd) {

		RequestJson result = new RequestJson();

		// 根据手机号查询用户名
		String loginname = userService.selectLoginNameByPhone(phone);

		if (StringUtils.isEmpty(loginname)) {
			result.setMsg("手机号未绑定帐号");
			result.setResultCode(OwnerConstants.PHONE_NOT_BIND_ACCOUNT);
			result.setSuccess(false);
			
		} else {
			CommonVerifyCode verifyCode = commonVerifyCode.selectCodeByPhone(phone);
			String codes = verifyCode.getCode();
			Date expireTime = verifyCode.getExpireTime();
			Date date = new Date();

			if ((date.compareTo(expireTime)) < 0) {
				
				if (code.equals(codes)) {
					ouserService.forgetPass(pwd, loginname);
					result.setMsg("成功操作！");
					result.setResultCode(OwnerConstants.PHONE_BIND_SUCCESS);
					result.setSuccess(true);
				} else {
					result.setMsg("输入验证码有误！");
					result.setSuccess(false);
					result.setResultCode(OwnerConstants.CODE_IS_FALSE);
				}
			} else {
				result.setMsg("验证码失效，请重新获取");
				result.setSuccess(false);
				result.setResultCode(OwnerConstants.CODE_IS_INVALIDE);
			}
		}
		return result;
	}
	
    /**
     * @Description 获取该区域下面的楼栋、单元、门牌号<br>
     * 
     * @param regionId 区域id
     * @return 返回该区域下面的楼栋、单元、门牌号
     * @author caiyinli 13277030520@163.com
     * @date 2016年6月29日
     * @see 
     */
    @RequestMapping(value = "getBuildingAndUnitAndHouse")
    @ResponseBody
    public RequestJson getBuildingAndUnitAndHouse(String regionId) {
        
        RequestJson result = new RequestJson();
       
        try {
        	List<CellBuilding> cells = cellBuildingService.getBuildingAndUnitAndHouse(regionId);
        	
			result.setMsg("数据获取成功！");
			result.setResultCode(OwnerConstants.PHONE_BIND_SUCCESS);
			result.setSuccess(true);
			result.setObj(cells);
		} catch (Exception e) {
			e.printStackTrace();
			result.setMsg("数据获取失败！");
			result.setResultCode(OwnerConstants.CODE_IS_FALSE);
			result.setSuccess(false);
		}
        

        return result;
    }
    
	/**
	 * @Description <br>
	 * 
	 * @param nickname 业主昵称
	 * @param userName 业主真实姓名
	 * @param sex 业主性别
	 * @param email 业主邮箱
	 * @param token
	 * @return resultCode = 0：操作成功 resultCode = 其他：操作失败
	 * @author caiyinli 13277030520@163.com
	 * @date 2016年6月29日
	 * @see 
	 */
	@RequestMapping(value = "saveOrUpdateMemberInfo")
	@ResponseBody
	public RequestJson saveOrUpdateMemberInfo(String nickname, String userName, Integer sex,String email, String token) {
		
		RequestJson result = new RequestJson();
		
		try {
			result = commomTokenService.OrderInteractState(token , result);
			if (result.isSuccess()) {
				//通过token获取当前用户
				CommonToken tokenInfo = commomTokenService.selectByToken(token);
				String loginname = tokenInfo.getAccount();
				User user = userService.selectByLoginName(loginname);
				
				if (StringUtils.isNotEmpty(nickname)) {
					user.setNickname(nickname);
				}
				
				if(StringUtils.isNotEmpty(userName)){
					user.setUsername(userName);
				}
				
				if (sex != null) {
					user.setSex(sex);
				}
				
				if (StringUtils.isNotEmpty(email)) {
					user.setEmail(email);
				}
				
				user.setModifydatetime(DateUtils.getTimestamp());
				//保存和修改用户信息
				int flag = userService.updateByPrimaryKeySelective(user);
				
				if(flag == Constants.SQL_RESULT_SUCCESS){
					result.setResultCode(OwnerConstants.UPDATE_INFO_SUCCESS);
					result.setSuccess(true);
					result.setObj(user);
					result.setMsg("修改成功！");
				}else{
					result.setResultCode(OwnerConstants.UPDATE_INFO_FALSE);
					result.setSuccess(false);
					result.setMsg("修改失败！");
				}
				
			}
		} catch (Exception e) {
			result.setSuccess(false);
			result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
			result.setMsg("网络异常");
		}
		
		return result;
	}
}
